package com.chx.service.impl;

import com.chx.dao.UserDAO;
import com.chx.entity.User;
import com.chx.service.UserService;
import com.chx.utils.SaltUtils;
import com.chx.utils.VerifyCodeUtils;
import com.chx.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserDAO userDAO;

    private static final String VERIFYKEY="verifyCode";

    @Override
    public void getVerifyCode(HttpSession httpSession,HttpServletResponse response) {
        String s = VerifyCodeUtils.generateVerifyCode(4);
        httpSession.setAttribute(VERIFYKEY,s);
        response.setContentType("image/png");
        try {
            VerifyCodeUtils.outputImage(100,50,response.getOutputStream(),s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void login(HttpSession httpSession,UserVo vo) {
        String s = (String)httpSession.getAttribute(VERIFYKEY);
        try {
            if (vo.getVerifyCode().equalsIgnoreCase(s)) {
                Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(vo.getUsername(), vo.getPassword()));
            }
        }catch (UnknownAccountException e){
            System.out.println("用户名错误");
            throw e;
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
            throw e;
        }catch (Exception e){
            throw e;
        }
    }

    @Override
    public void register(UserVo vo) {
        User user = new User();
        String salt = SaltUtils.getSalt(8);
        Md5Hash md5Hash = new Md5Hash(vo.getPassword(),salt,1024);
        user.setUsername(vo.getUsername());
        user.setPassword(md5Hash.toHex());
        user.setSalt(salt);
        userDAO.insertUser(user);
    }
}
